package com.cs.client;

import com.cs.code.RpcEncoder;
import com.cs.entity.RpcRequest;
import com.cs.serialize.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.cs.client.ClientBootStrap.curator;
import static com.cs.client.ClientBootStrap.serverMap;


public class RpcConsumer {

    //创建线程池对象
    public static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private  UserClientHandler userClientHandler;

    private  RpcRequest rpcRequest;
    private ChannelFuture channelFuture;
    private EventLoopGroup group = new NioEventLoopGroup();

    private Bootstrap bootstrap = new Bootstrap();

    private String ip;
    private int port;
    private String value;
    private String path;

    public RpcConsumer() {

        if(serverMap.size()==0){
            throw new RuntimeException("未获取到任何服务器信息");
        }

        String key = doBalance(serverMap);//通过负载均衡策略选择最优服务

        //赋值
        String[] values = serverMap.get(key).split(",");
        String[] ipPort = values[0].split(":");
        this.value = values[0];
        this.ip = ipPort[0];
        this.port = Integer.valueOf(ipPort[1]);
        this.path = key;

        System.out.println("被选择的服务===="+path+":::"+value);
    }

    /**
     * 负载均衡
     * @param serverMap
     * @return
     */
    private String doBalance(ConcurrentHashMap<String, String> serverMap) {

        List<String> keys = new ArrayList<>();//最短响应时间的服务节点地址集合
        int shortest=5000;//最短响应时间，默认最大值5秒
        for(String key : serverMap.keySet()){

            String[] strings = serverMap.get(key).split(",");
            int ackTime = Integer.valueOf(strings[1]);

            if(shortest>ackTime){//相对响应时间短的服务被选择
                shortest = ackTime;//记录最短的响应时间
                keys.clear();//清空响应时间长的服务地址
                keys.add(key);//记录响应时间短的服务地址
            }else if(shortest==ackTime){
                keys.add(key);//添加响应时间相同的服务地址
            }

        }

        if(keys.size()==0){
            throw new RuntimeException("未获取到任何合格的服务器信息");
        }

        int index = (int) (Math.random() * keys.size());//随机获取一个范围内的index

        return keys.get(index);
    }


    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法

                initClient();

                //被代理类
                rpcRequest.setClassName(method.getDeclaringClass().getName());
                //被代理方法
                rpcRequest.setMethodName(method.getName());
                //传输数据内容
                rpcRequest.setParameters(args);
                Class[] classes = new Class<?>[args.length];
                for (int i =0;i<args.length;i++) {
                    classes[i] = args[i].getClass();
                }
                //传输数据类型
                rpcRequest.setParameterTypes(classes);

                // 设置参数：通信协议对象,zookeeper客户端,连接服务节点地址
                userClientHandler.setPara(rpcRequest,path,value);
                if(!channelFuture.channel().isActive()){
                    throw new RuntimeException("服务器异常！");
                }
                return executor.submit(userClientHandler).get();
            }
        });


    }

    //2.初始化netty客户端
    public void initClient() throws InterruptedException {
        if(ip==null||ip.isBlank()){
            System.err.println("未输入IP地址");
        }
        if(port==0){
            System.err.println("未输入断开地址");
        }

        userClientHandler = new UserClientHandler();
         //初始化通信协议对象，并生成UUID作为当前客户端ID
        rpcRequest = new RpcRequest();
        rpcRequest.setRequestId(UUID.randomUUID().toString());

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 设置超时时间
                        pipeline.addLast("idleStateHandler",new IdleStateHandler(5, 5, 5, TimeUnit.SECONDS));

                        pipeline.addLast("decoder",new StringDecoder());
                        pipeline.addLast("encoder",new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast("channelHandler",userClientHandler);

                    }
                });
        channelFuture = bootstrap.connect(ip,port).sync();
        System.out.println("向服务器 "+ip+":"+port+" 发起请求");
    }


}
